
window.chatHub = async function (layer, view, layui) {
    if (layui.sessionData(layui.setter.tableName)["UserInfo"]) {
        const connection = new signalR.HubConnectionBuilder()
            .withUrl(layui.setter.baseUrl + "/hub", { accessTokenFactory: () => layui.sessionData(layui.setter.tableName)["UserInfo"]?.auth_token?.token })
            .withAutomaticReconnect()
            .configureLogging(signalR.LogLevel.Error)
            .build();

        //强制下线
        connection.on("ForceSignOut", () => {
            layer.alert("已有用户登录,强制下线", {
                skin: 'layui-layer-molv',
                closeBtn: 0
            }, function () {
                view.exit();
            });
        });

        //超时强制下线
        connection.on("TimeOut", () => {
            layer.alert("超时强制下线", {
                skin: 'layui-layer-molv',
                closeBtn: 0
            }, function () {
                view.exit();
            });
        });

        //提醒另一个用户已登录
        connection.on("signOut", (message) => {
            layer.confirm(message, {
                btn: ['确定', '取消'],
                skin: 'layui-layer-molv',
                closeBtn: 0
            }, function (index, layero) {
                connection.invoke("ForceSignOut");
                layer.close(index)
            }, function () {
                view.exit();
            });
        });

        connection.on("SetOnlineNumber", (number) => {
            console.log(`当前在线人数：${number}`);
        });
        connection.on("ShowSystemInfo", (msg) => {
            console.log(msg);
        });
        connection.on("ErroMsg", (msg) => {
            console.log(msg);
        });
        await connection.start();

        //connection.on("showMessage", (message) => {
        //    parent.layer.msg(message);
        //});

        connection.onclose(function () {
            // 连接关闭后执行的代码
            setTimeout(async () => await connection.start(), 5000); // 5秒后重新连接
        });
    }
}